<?php
/**
 * @package  nuo.router
 * @author   Nam Nguyen <nam.ngvan@gmail.com>
 * @version  1.0
 * @since    Apr 17, 2013
 */
class Nuo_Router
{
	/**
	 * Routes instance
	 * @access  private
	 * @var     array
	 */
	private $_vars = array();

	/**
	 * directory maps
	 * @var array
	 */
	private $_dirs = array(
		'admincp' => 'controller/admincp',
		'mobile' => 'controller/mobile',
		'browse' => 'controller/browse',
		'default' => 'controller/browse',
	);

	/**
	 */
	public function __construct()
	{
		$key = 'core/config/route';

		$data = Nuo_Cache::instance() -> read($key);

		if (FALSE == $data)
		{
			$sql = 'select * from nuo_core_route where is_enabled=1 order by sort_order desc';
			$data = Database::instance() -> fetchAll($sql);
			Nuo_Cache::instance() -> write($key, $data);
		}

		foreach ($data as $row)
		{
			if (NULL != ($class = $row['class_name']))
			{
				if ($row['file_name'])
				{
					require_once MODULE_DIR . $row['file_name'];
				}
				$this -> _vars[$row['name']] = new $class;
			}
		}

	}

	/**
	 * @access   public
	 * @param    string $name
	 * @param    string $value
	 * @return   void
	 */
	public function setDir($name, $name)
	{
		$this -> _dirs[$name] = $name;
	}

	/**
	 * Get controller directory
	 * @param    string $name
	 * @return string
	 */
	public function getDir($name = 'default')
	{
		if (isset($this -> _dirs[$name]))
		{
			return $this -> _dirs[$name];
		}
		return false;
	}

	/**
	 * Add new Router
	 * @static
	 * @param string $name
	 * @param Route_Null $route
	 * @return void
	 */
	public function addRoute($name, $route)
	{
		$this -> _vars[$name] = $route;
	}

	/**
	 * Caculate to set request params and action name
	 * @param    Nuo_Request  $request
	 * @return   bool
	 */
	public function execute($request)
	{
		$parts = explode('/', $request -> getPath());

		foreach ($this->_vars as $route)
		{
			if ($route -> match($request, $parts))
			{
				return TRUE;
			}
		}

		$notfound = 'core/' . $this -> getDir() . '/error404';

		$request -> setName($notfound);

		// go to not found page
		return FALSE;
	}

}
